package org.dei.perla.rockfall;

import java.io.BufferedReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Iterator;

import org.dei.dataserver.Server;
import org.dei.perla.parser.expressions.Constant;
import org.dei.perla.parser.expressions.ConstantID;
import org.dei.perla.parser.grammar.ParseException;
import org.dei.perla.parser.grammar.Parser;
import org.dei.perla.parser.statements.Query;
import org.dei.perla.parser.util.PairValue;
import org.dei.perla.rockfall.utils.DatabaseDump;
import org.dei.perla.sys.device.fpc.dspic.DSPicFPC;
import org.dei.perla.sys.environments.ActiveSession;
import org.dei.perla.sys.environments.Environment;
import org.dei.perla.sys.environments.QueryAnalyzer;
import org.dei.perla.sys.environments.SetEnvironment;
import org.dei.perla.sys.query.llqruntime.datacollection.*;
import org.dei.perla.sys.query.sqruntime.SetInformation;


public class RockfallManager {

	private static final int MAX_FPC = 4;

	private ArrayList<DSPicFPC> dspicList;

	private static boolean firstRun = true;

	public RockfallManager() {

		dspicList = new ArrayList<DSPicFPC>();

		// Inizializzo il server
		Server s = new Server(5606);
		s.start();

		// Istanzio ed aggancio le fpc al server ed al database dumper
		for (int i = 0; i < MAX_FPC; i++){
			DSPicFPC tTempFpc = new DSPicFPC(s.getFpcPipes(i), i);
			dspicList.add(tTempFpc);
			Thread dbDump = new Thread(new DatabaseDump(tTempFpc.registerQuery(null)));
			dbDump.start();
		}
	}

	public Iterator<DSPicFPC> getDSPicIterator() {
		return dspicList.iterator();
	}

	public void executeQuery(String query) {

		StringReader reader = new StringReader(query);

		ArrayList<PairValue<String, ? extends Constant>> pAttributeToSetList = new ArrayList<PairValue<String, ? extends Constant>>();

		if (firstRun) {
			new Parser(new BufferedReader(reader));
			firstRun = false;

		} else {
			Parser.ReInit(new BufferedReader(reader));
		}

		try {
			Query parsedQuery = Parser.StatementSequence();


			QueryAnalyzer.registerQuery(parsedQuery);
			Environment tEnv;
			SetInformation tInfo;
			while (ActiveSession.getActiveEnvironments().hasNext()) {
				tEnv = ActiveSession.getActiveEnvironments().next();
				if (tEnv instanceof SetEnvironment) {
					SetEnvironment tSEnv = (SetEnvironment) tEnv;
					tInfo = tSEnv.getSetInformation();

					for (String tAttributeToSet : tInfo.getAttributeToSet().keySet()){

						pAttributeToSetList.add(new PairValue<String, Constant>(tAttributeToSet, tInfo.getAttributeToSet().get(tAttributeToSet)));
					}

					for (ConstantID id : tInfo.getDevicesToSet()) {
						dspicList.get(id.getValueInt()).setUpdateAttributes(pAttributeToSetList);
					}

				}
			}




		} catch (ParseException e) {
			e.printStackTrace();
		} 
	}
}
